package com.qf.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.dto.LoginDto;
import com.qf.entity.SysUser;
import com.qf.mapper.SysUserMapper;
import com.qf.model.Result;
import com.qf.service.ISysUserService;
import com.qf.utils.PasswordEncoder;
import com.qf.utils.JwtUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 作者；雷明旭
 * 时间；2021/11/29:57
 * bug退散bug退散bug退散
 */

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    private SysUserMapper sysUserMapper;
    private PasswordEncoder passwordEncoder;
    private JwtUtils jwtUtils;

    public SysUserServiceImpl(SysUserMapper sysUserMapper, PasswordEncoder passwordEncoder, JwtUtils jwtUtils) {
        this.sysUserMapper = sysUserMapper;
        this.passwordEncoder = passwordEncoder;
        this.jwtUtils = jwtUtils;
    }

    @Override
    public Result SysLogin(LoginDto loginDto) {
        //TODO 验证用户名密码，如果正确生成token
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginDto.getUsername());

        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        //校验密码
        if(null == sysUser|| !passwordEncoder.matches(loginDto.getPassword(),sysUser.getPassword())){
            //密码错误
            return Result.buildFailure("用户名或密码错误");
        }else {
            //密码正确，生成token

            Map<String,String> token = new HashMap<>();

            String username = loginDto.getUsername();

            token.put(JwtUtils.ACCESS_TOKEN_KEY,jwtUtils.createAccessToken(username));
            token.put(JwtUtils.REFRESH_TOKEN_KEY,jwtUtils.createRefreshToken(username));

            return Result.buildSuccess(token);
        }
    }
}
